<?php
namespace app\single\controller;
use think\Db;
/**
 * #用户产品秀 {关于用户管理相关}
 */
class Product extends Common{
    private $artcate_id=5; //产品秀分类ID

    function setting($isJson=true){
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id,vip_expire,coin,coin_expire');
        $vip_level=model('member')->isVip($uid);
        $_coin=config('setting.article_coin');
        $nums2=(int)config('setting.article_nums'); //每日可发产品数量
        $has=model('article')->where([
            'uid'=>$user['id'],
            's_time'=>['s_time','>=',strtotime(date('Y-m-d'))]
        ])->count();
        $nums=$nums2-$has; //该用户今日可发产品数量
        if($nums<0){
            $nums=0;
        }
        $isFirst=model('article')->where(['uid'=>$user['id']])->count();
        if($vip_level){
            if($isFirst){
                $_coin=config('setting.vip_article_coin');
            }else{
                $_coin=config('setting.vip_first_article_coin');
            }
        }
        
        
        $res=[
            'vip_level'=>$vip_level,
            'money'=>$_coin,
            'coin'=>$user['coin_expire']>time()?99999:$user['coin'],
            'coin_expire'=>$user['coin_expire'],

            'nums'=>$nums, //该用户今日可发产品数量
            'nums2'=>$nums2, //每日最多可发产品数量
            'count'=>$isFirst, //已发产品数量
            // 最大可发
            'max'=>$vip_level+config('setting.article_counts')+config('setting.article_vip_counts_inc'),
        ];
        if($isJson){
            return json('',0,$res);
        }
        return $res;
    }

    /**
     * 获取产品秀的二级分类
     * @return [type] [description]
     */
    function getCates($isJson=true){
        // 获取产品秀的二级分类
        $cate =model('artcate')->readAll([
            'pid'=>$this->artcate_id,
            'status'=>1,
        ],0,[
            'field'=>'id,name,icon'
        ])->toArray();
        $ids=[];
        $prefix=request()->domain().'/tagsicon/';
        foreach($cate as $k => $v) {
            if(!empty($v['icon'])){
                $cate[$k]['icon']=$prefix.$v['icon'];
            }
            $ids[]=$v['id'];
        }
        if($isJson){
            return json('',0,$cate);
        }
        return [$cate,$ids];
    }
    /**
     * 查询产品秀列表
     * @return json
     */
    function index(){
        $cate=$this->getCates(false);
        $data = [
            'cate'=>$cate[0]
        ];
        $map=[
            'status'=>1,
            'cate_id'=>['cate_id','in',$cate[1]],
        ];
        $options=[
            'order'=>'browse desc',
            'with'=>['author','cate','praise','images'],
            'field'=>'id,uid,cate_id,wxId,tel,title,content,s_time,browse,praise,belittle'
        ];

        $list=model('article')->readAll($map,3,$options)->toArray();
        $hot=[];
        foreach ($list['data'] as $key => $value) {
            if(isset($value['head_img'])&&!is_null($value['head_img'])){
                $value['head_img']=images($value['head_img']);
            }
            foreach ($value['images'] as $k => $v) {
                $value['images'][$k]['link']=images($v['link']);
            }
            $hot[]=$value;
        }

        $options['order']='s_time desc';
        $list=model('article')->readAll($map,10,$options)->toArray();
        $new=[];
        foreach ($list['data'] as $key => $value) {
            if(isset($value['head_img'])&&!is_null($value['head_img'])){
                $value['head_img']=images($value['head_img']);
            }
            foreach ($value['images'] as $k => $v) {
                $value['images'][$k]['link']=images($v['link']);
            }
            $new[]=$value;
        }

        // 整合数据
        $data['hot'] = $hot;
        $data['news'] = $new;
        return json('',0,$data);
    }


    

    /**
     * 发布产品(松散型的)
     * @param  integer $cate_id 分类ID
     * @param  string $title 文章标题
     * @param  string $content 文章内容
     * @return json
     */
    function add(){
        $uid=$this->user['id'];
        $time=time();
        $setting=$this->setting(false);

        if($setting['coin_expire']<$time&&$setting['coin']<$setting['money']){
            //return json('您的'.lang('coin').'不足');
        }
        if($setting['count']>=$setting['max']){
            //return json("您最多可拥有{$setting['max']}份产品秀，升级VIP级别可扩增数量");
        }
        if($setting['nums']<=0){
            //return json("今日发布已达上限，请明日再来");
        }
        $data=[
            'cate_id'=>input('cate_id/d'),
            'title'=>input('title/s'),
            'content'=>input('content/s'),
            'tel'=>input('tel/s'),
            'wxId'=>input('wxId/s'),
        ];
        $validate=$this->validate($data,[
            'cate_id|分类'=>'require|min:1',
            'title|产品标题'=>'require',
            'content|产品内容'=>'require',
            'wxId|微信号'=>'require',
            'tel|手机号'=>'require|mobile',
        ]);
        if(true!==$validate){
            return json($validate,1);
        }
        // if(preg_match("/([\x{4e00}-\x{9fa5}]+)/u", $data['wxId'])){   
        //     return json('微信号不能好友中文字符',1);
        // }
        // if(preg_match("/[~！@#￥%……&*（）——+“：|{}”《》？·、‘；、。，【】]+/", $data['wxId'])){
        //     return json('微信号不能好友中文字符',1);
        // }
        if(preg_match('/[^A-Za-z0-9]/', $data['wxId'])){
            return json('微信号仅允许为字母和数字的组合',1);
        }
        $files=request()->file('file');
        // 判断必填项是否已经达到要求
        if (count($files) < 3) {
            return json('图片数量不足3张',1);
        }
        $data['s_time']=time();
        $data['uid']=$uid;
        $module=model('artmodule')->read(['name'=>request()->module()],'id');
        $data['module_id']=$module['id'];
        

        $result=true;
        $add=[];
        Db::startTrans();
        try{
            // 执行添加
            $add = model('article')->add($data);
            if(empty($add)){
                exception('发布产品失败');
            }
            $medias=[];
            foreach ($files as $v) {
                $res=$this->loadHeadImg($v);
                if($res['success']){
                    $medias[]=[
                        'product_id'=>$add['id'],
                        'link'=>$res['msg'],
                        'type'=>1,
                    ];
                }
            }
            if(!empty($medias)){
                $e=model('media')->add($medias);
                if(empty($e)){
                    exception('图片文件写入失败');
                }
            }
            //扣除微豆
            if($setting['money']>0){
                if($setting['coin_expire']<$time){
                    $dec=model('member')->where([
                        'id'=>$uid,
                        'coin'=>['coin','>=',$setting['money']]
                    ])->setDec('coin',$setting['money']);
                    if(!$dec){
                        exception(lang('coin').'扣除失败');
                    }
                }
                
                $log=model('coinlog')->add(
                    [
                        'nums'=>0-$setting['money'],
                        'time'=>$time,
                        'uid'=>$uid,
                        'type'=>0,
                        'remark'=>'发布产品秀消耗',
                    ]
                );
                if(empty($log)){
                    exception('写入记录失败，请稍后再试');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result=$e->getMessage();
        }
        if(true!==$result){
            return json($result,1);
        }
        return json('发布产品成功');
            
    }
    /**
     * 更多的热门产品
     * @return [type] [description]
     */
    function hots(){
        $cate=$this->getCates(false);
        $data = [
            'cate'=>$cate[0]
        ];
        $map=[
            'status'=>1,
            'cate_id'=>['cate_id','in',$cate[1]],
        ];
        $options=[
            'order'=>'browse desc',
            'with'=>['author','cate','praise','images'],
            'field'=>'id,uid,cate_id,wxId,tel,title,content,s_time,browse,praise,belittle'
        ];

        $list=model('article')->readAll($map,5,$options)->toArray();
        $hot=[];
        foreach ($list['data'] as $key => $value) {
            foreach ($value['images'] as $k => $v) {
                $value['images'][$k]['link']=images($v['link']);
            }
            $hot[]=$value;
        }
        return json('',0,$hot);
    }

    /**
     * 查询产品列表
     * @param  integer $cate_id 产品秀二级分类ID
     * @param  integer $mine    0：获取所有 1：获取我发布的
     * @return json
     */
    function product($cate_id=0,$mine=0){
        $map=[
            'status'=>1,
        ];
        if($cate_id>0){
            $has=model('artcate')->where(['id'=>$cate_id,'pid'=>$this->artcate_id])->count();
            if($has){
                $map['cate_id']=$cate_id;
            }
        }else{
            $cate=$this->getCates(false);
            $map['cate_id']=['cate_id','in',$cate[1]];
        }
        if($mine>0){
            $map['uid']=$this->user['id'];
        }
        
        $options=[
            'order'=>'s_time desc',
            'with'=>['author','cate','praise','images'],
            'field'=>'id,uid,cate_id,wxId,tel,title,content,s_time,browse,praise,belittle'
        ];

        $list=model('article')->readAll($map,true,$options)->toArray();
        $res=[];
        foreach ($list['data'] as $key => $value) {
            if(isset($value['head_img'])&&!is_null($value['head_img'])){
                $value['head_img']=images($value['head_img']);
            }
            foreach ($value['images'] as $k => $v) {
                $value['images'][$k]['link']=images($v['link']);
            }
            $res[]=$value;
        }
        $list['data']=$res;
        return json('',0,$list);
    }
    /**
     * 查询产品秀产品详情
     * @param  integer $aid 文章ID
     * @return [type]      [description]
     */
    function info($id=0){
        $map=[
            'id'=>$id,
            'status'=>1,
        ];
        $options=[
            'with'=>['author','cate','images'],
        ];
        $field='id,uid,wxId,tel,title,s_time,cate_id,content,browse,praise,belittle';

        $info=model('article')->read($map,$field,$options);
        if(isset($info['head_img'])&&!is_null($info['head_img'])){
            $info['head_img']=images($info['head_img']);
        }
        if(isset($info['images'])){
            foreach ($info['images'] as $k => $v) {
                $info['images'][$k]['link']=images($v['link']);
            }
            // 增加浏览量
            $this->clicks($id);
        }
        if(isset($info['id'])){
            $info['is_parise']=null;
            $parise=model('praise')->read(['product_id'=>$info['id']],'convert(type,char(1)) as type');
            if(isset($parise)){
                $info['is_parise']=$parise['type'];
            }
        }
        return json('',0,$info);
    }
    /**
     * 文章点赞、贬低
     * @param  integer $id   文章ID
     * @param  integer $type 0：浏览（查询文章详情时调用）、1：点赞 2：贬低
     * @return json
     */
    function clicks($id=0,$type=0){
        $map=[
            'id'=>$id,
        ];
        if($type==0){ //浏览量
            model('article')->where($map)->setInc('browse');
            return json('');
        }elseif($type==1){ //点赞
            $uid=$this->user['id'];
            $has=model('praise')->where(['uid'=>$uid,'product_id'=>$id])->count();
            if($has){
                return json('您已经点过赞了',1);
            }
            $e=model('article')->where($map)->setInc('praise');
            if($e){
                model('praise')->add([
                    'uid'=>$uid,
                    'product_id'=>$id,
                    'type'=>1,
                ]);
            }
            return json('点赞成功');
        }elseif($type==2){ //贬低
            $uid=$this->user['id'];
            $has=model('praise')->where(['uid'=>$uid,'product_id'=>$id])->count();
            if($has){
                return json('您已经点过赞了',1);
            }
            $e=model('article')->where($map)->setInc('belittle');
            if($e){
                model('praise')->add([
                    'uid'=>$uid,
                    'product_id'=>$id,
                    'type'=>2,
                ]);
            }
            return json('谢谢点评');
        }
        return json('');
        
    }
}